package com.es.demo;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class ElasticSearchServiceImpl implements ElasticSearchService {
    private static final Logger logger = LoggerFactory.getLogger(ElasticSearchServiceImpl.class);

    private final TransportClient transportClient;

    private static List<String> nodes = new ArrayList<String>();

    private static final String CLUSTER_NAME = "simon-es-cluster";

    static {
        String nodeStr = "127.0.0.1:9300;127.0.0.1:9301;127.0.0.1:9302";

        for (String strings : StringUtils.split(nodeStr, ";")) {
            String[] node = StringUtils.split(strings, ":");
            if (ArrayUtils.getLength(node) != 2) {
                throw new IllegalArgumentException("Illegal cluster.nodes: " + nodes);
            }
            nodes.add(strings);
        }
    }

    public ElasticSearchServiceImpl() {
        logger.info("Init cluster.nodes: {}", nodes);
        Settings settings = Settings.builder().put("cluster.name", CLUSTER_NAME).put("client.transport.sniff", true).build();
        this.transportClient = new PreBuiltTransportClient(settings);

        nodes.forEach(node -> {
            String[] items = StringUtils.split(node, ":");
            String host = items[0];
            int port = Integer.parseInt(items[1]);
            try {
                TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName(host), port);
                transportClient.addTransportAddresses(transportAddress);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public Client getClient() {
        return this.transportClient;
    }

    public void destroy() {
        transportClient.close();
    }

}
